package cn.denvie.agent.configsource;

import org.stagemonitor.configuration.source.AbstractConfigurationSource;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * A variation of {@link org.stagemonitor.configuration.source.PropertyFileConfigurationSource} (under Apache license 2.0)
 * which does not initialize a logger.
 * <p>
 * This is important when using this configuration source to configure the logger.
 * </p>
 */
public final class PropertyFileConfigurationSource extends AbstractConfigurationSource {

    private final String location;
    private Properties properties;

    public PropertyFileConfigurationSource(String location) {
        this.location = location;
        reload();
    }

    public static boolean isPresent(String location) {
        return getProperties(location) != null;
    }

    private static Properties getProperties(String location) {
        if (location == null) {
            return null;
        }
        Properties props = getFromClasspath(location, ClassLoader.getSystemClassLoader());
        if (props == null) {
            props = getFromFileSystem(location);
        }
        /*for (Map.Entry<Object, Object> entry : props.entrySet()) {
            System.out.println("Property key = " + entry.getKey() + ", value = " + entry.getValue());
        }*/
        return props;
    }

    public static Properties getFromClasspath(String classpathLocation, ClassLoader classLoader) {
        final Properties props = new Properties();
        try (InputStream resourceStream = classLoader.getResourceAsStream(classpathLocation)) {
            if (resourceStream != null) {
                props.load(resourceStream);
                return props;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Properties getFromFileSystem(String location) {
        Properties props = new Properties();
        try (InputStream input = new FileInputStream(location)) {
            props.load(input);
            return props;
        } catch (FileNotFoundException ex) {
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void reload() {
        properties = getProperties(location);
        if (properties == null) {
            properties = new Properties();
        }
    }

    @Override
    public String getName() {
        return location;
    }

    @Override
    public String getValue(String key) {
        return properties.getProperty(key);
    }

}